<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="180px"
      v-loading="formLoading"
    >
      <el-form-item label="退换货单号" prop="returnNo">
        <el-input v-model="formData.returnNo" placeholder="请输入退换货单号" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderId">
        <el-input v-model="formData.orderId" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="订单号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单号" />
      </el-form-item>
      <el-form-item label="客户编号" prop="customerId">
        <el-input v-model="formData.customerId" placeholder="请输入客户编号" />
      </el-form-item>
      <el-form-item label="类型" prop="returnType">
        <el-select v-model="formData.returnType" placeholder="请选择类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_RETURN_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退换货原因" prop="returnReason">
        <el-input v-model="formData.returnReason" placeholder="请输入退换货原因" />
      </el-form-item>
      <el-form-item label="原因描述" prop="returnReasonDesc">
        <el-input v-model="formData.returnReasonDesc" placeholder="请输入原因描述" />
      </el-form-item>
      <el-form-item label="退换货总数量" prop="totalQuantity">
        <el-input v-model="formData.totalQuantity" placeholder="请输入退换货总数量" />
      </el-form-item>
      <el-form-item label="退换货总金额" prop="totalAmount">
        <el-input v-model="formData.totalAmount" placeholder="请输入退换货总金额" />
      </el-form-item>
      <el-form-item label="退款金额" prop="refundAmount">
        <el-input v-model="formData.refundAmount" placeholder="请输入退款金额" />
      </el-form-item>
      <el-form-item label="货币代码" prop="currencyCode">
        <el-input v-model="formData.currencyCode" placeholder="请输入货币代码" />
      </el-form-item>
      <el-form-item label="状态" prop="returnStatus">
        <el-radio-group v-model="formData.returnStatus">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_RETURN_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="申请时间" prop="applyTime">
        <el-date-picker
          v-model="formData.applyTime"
          type="date"
          value-format="x"
          placeholder="选择申请时间"
        />
      </el-form-item>
      <el-form-item label="审批时间" prop="approveTime">
        <el-date-picker
          v-model="formData.approveTime"
          type="date"
          value-format="x"
          placeholder="选择审批时间"
        />
      </el-form-item>
      <el-form-item label="审批人" prop="approveUser">
        <el-input v-model="formData.approveUser" placeholder="请输入审批人" />
      </el-form-item>
      <el-form-item label="审批备注" prop="approveRemark">
        <el-input v-model="formData.approveRemark" placeholder="请输入审批备注" />
      </el-form-item>
      <el-form-item label="退货截止时间" prop="returnDeadline">
        <el-date-picker
          v-model="formData.returnDeadline"
          type="date"
          value-format="x"
          placeholder="选择退货截止时间"
        />
      </el-form-item>
      <el-form-item label="退货地址编号" prop="returnAddressId">
        <el-input v-model="formData.returnAddressId" placeholder="请输入退货地址编号" />
      </el-form-item>
      <el-form-item label="退货配送方式" prop="returnShippingMethod">
        <el-input v-model="formData.returnShippingMethod" placeholder="请输入退货配送方式" />
      </el-form-item>
      <el-form-item label="退货运单号" prop="returnTrackingNo">
        <el-input v-model="formData.returnTrackingNo" placeholder="请输入退货运单号" />
      </el-form-item>
      <el-form-item label="退货发货时间" prop="returnShipTime">
        <el-date-picker
          v-model="formData.returnShipTime"
          type="date"
          value-format="x"
          placeholder="选择退货发货时间"
        />
      </el-form-item>
      <el-form-item label="退货收货时间" prop="returnReceiveTime">
        <el-date-picker
          v-model="formData.returnReceiveTime"
          type="date"
          value-format="x"
          placeholder="选择退货收货时间"
        />
      </el-form-item>
      <el-form-item label="质检结果" prop="qualityCheckResult">
        <el-input v-model="formData.qualityCheckResult" placeholder="请输入质检结果" />
      </el-form-item>
      <el-form-item label="质检时间" prop="qualityCheckTime">
        <el-date-picker
          v-model="formData.qualityCheckTime"
          type="date"
          value-format="x"
          placeholder="选择质检时间"
        />
      </el-form-item>
      <el-form-item label="质检员" prop="qualityCheckUser">
        <el-input v-model="formData.qualityCheckUser" placeholder="请输入质检员" />
      </el-form-item>
      <el-form-item label="退款方式" prop="refundMethod">
        <el-input v-model="formData.refundMethod" placeholder="请输入退款方式" />
      </el-form-item>
      <el-form-item label="退款时间" prop="refundTime">
        <el-date-picker
          v-model="formData.refundTime"
          type="date"
          value-format="x"
          placeholder="选择退款时间"
        />
      </el-form-item>
      <el-form-item label="退款交易ID" prop="refundTransactionId">
        <el-input v-model="formData.refundTransactionId" placeholder="请输入退款交易ID" />
      </el-form-item>
      <el-form-item label="客户留言" prop="customerMessage">
        <el-input v-model="formData.customerMessage" placeholder="请输入客户留言" />
      </el-form-item>
      <el-form-item label="内部备注" prop="internalNotes">
        <el-input v-model="formData.internalNotes" placeholder="请输入内部备注" />
      </el-form-item>
      <el-form-item label="附件URL列表JSON" prop="attachments">
        <el-input v-model="formData.attachments" placeholder="请输入附件URL列表JSON" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { OrderReturnApi, OrderReturnVO } from '@/api/crossborder/orderreturn'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

/** 跨境电商退换货申请 表单 */
defineOptions({ name: 'OrderReturnForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  returnNo: undefined,
  orderId: undefined,
  orderNo: undefined,
  customerId: undefined,
  returnType: undefined,
  returnReason: undefined,
  returnReasonDesc: undefined,
  totalQuantity: undefined,
  totalAmount: undefined,
  refundAmount: undefined,
  currencyCode: undefined,
  returnStatus: undefined,
  applyTime: undefined,
  approveTime: undefined,
  approveUser: undefined,
  approveRemark: undefined,
  returnDeadline: undefined,
  returnAddressId: undefined,
  returnShippingMethod: undefined,
  returnTrackingNo: undefined,
  returnShipTime: undefined,
  returnReceiveTime: undefined,
  qualityCheckResult: undefined,
  qualityCheckTime: undefined,
  qualityCheckUser: undefined,
  refundMethod: undefined,
  refundTime: undefined,
  refundTransactionId: undefined,
  customerMessage: undefined,
  internalNotes: undefined,
  attachments: undefined,
})
const formRules = reactive({
  returnNo: [{ required: true, message: '退换货单号不能为空', trigger: 'blur' }],
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  orderNo: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  returnType: [{ required: true, message: '类型（1退货 2换货 3退款）不能为空', trigger: 'change' }],
  returnReason: [{ required: true, message: '退换货原因不能为空', trigger: 'blur' }],
  totalQuantity: [{ required: true, message: '退换货总数量不能为空', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '退换货总金额不能为空', trigger: 'blur' }],
  refundAmount: [{ required: true, message: '退款金额不能为空', trigger: 'blur' }],
  currencyCode: [{ required: true, message: '货币代码不能为空', trigger: 'blur' }],
  returnStatus: [{ required: true, message: '状态（10待审核 20已同意 30已拒绝 40待退货 50已退货 60已收货 70已退款 80已完成）不能为空', trigger: 'blur' }],
  applyTime: [{ required: true, message: '申请时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderReturnApi.getOrderReturn(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrderReturnVO
    if (formType.value === 'create') {
      await OrderReturnApi.createOrderReturn(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderReturnApi.updateOrderReturn(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    returnNo: undefined,
    orderId: undefined,
    orderNo: undefined,
    customerId: undefined,
    returnType: undefined,
    returnReason: undefined,
    returnReasonDesc: undefined,
    totalQuantity: undefined,
    totalAmount: undefined,
    refundAmount: undefined,
    currencyCode: undefined,
    returnStatus: undefined,
    applyTime: undefined,
    approveTime: undefined,
    approveUser: undefined,
    approveRemark: undefined,
    returnDeadline: undefined,
    returnAddressId: undefined,
    returnShippingMethod: undefined,
    returnTrackingNo: undefined,
    returnShipTime: undefined,
    returnReceiveTime: undefined,
    qualityCheckResult: undefined,
    qualityCheckTime: undefined,
    qualityCheckUser: undefined,
    refundMethod: undefined,
    refundTime: undefined,
    refundTransactionId: undefined,
    customerMessage: undefined,
    internalNotes: undefined,
    attachments: undefined,
  }
  formRef.value?.resetFields()
}
</script>